package cn.frh.user.controller;

import cn.frh.basic.exception.BusinessException;
import cn.frh.basic.util.AjaxResult;
import cn.frh.basic.util.PageList;
import cn.frh.user.domain.User;
import cn.frh.user.dto.UserDto;
import cn.frh.user.query.UserQuery;
import cn.frh.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口",description = "用户接口详细描述")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 查询一条数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User findById(@PathVariable("id") Long id){
        return userService.queryById(id);
    }
    //查询所有数据
    @GetMapping("/list")
    public List<User> findAll(){
        return userService.queryAll();
    }

    @PostMapping("/page")
    public PageList<User> queryPage(@RequestBody UserQuery query){
        return userService.queryPage(query);
    }
    @DeleteMapping("/{id}")
    public AjaxResult removeByUd(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("骚瑞~操作失败！");
        }
    }

    @PostMapping("/save")
    @ApiOperation(value = "用户添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if (user.getId() == null){
                userService.add(user);

            }else {
                userService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("骚瑞 操作失败");
        }
    }
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            userService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("骚瑞~操作失败！");
        }
    }
    @PostMapping("/register/phone")
    public AjaxResult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("骚瑞 系统错误");
        }
    }
}
